<template>
  <div id="updateUserInfo">
    <h2 class="mb-20">修改用户信息</h2>
    <el-form
      ref="formRef"
      style="max-width: 600px; margin-top: 15px"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      class="demo-formData"
      :size="formSize"
      status-icon
    >
      <el-form-item label="头像" prop="headPic" class="flex-c" style="text-align: left">
        <el-upload v-bind="uploadProps" style="width: 100%" class="avatar-uploader">
          <img v-if="formData.headPic" :src="formData.headPic" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="formData.nickName" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" disabled />
      </el-form-item>
      <el-form-item label="验证码">
        <el-input v-model="formData.captcha" style="flex: 1" />
        <el-button type="primary" class="ml-10" @click="sendCaptcha" :disabled="isSendCaptcha">{{
          isSendCaptcha ? `${countdown} 秒后重新获取` : '发送验证码'
        }}</el-button>
      </el-form-item>
      <div style="text-align: right; font-size: 12px">
        已有帐号?去
        <router-link to="/login"><span style="color: var(--main-color)">登录</span></router-link>
      </div>
      <el-row justify="center">
        <el-form-item>
          <el-button type="primary" @click="submitForm(formRef)"> 提交 </el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { getUserInfo, updateUserInfoCaptcha, updateUserInfo, presignedUrl } from '@/api'
import {
  ElMessage,
  type ComponentSize,
  type FormInstance,
  type FormRules,
  type UploadProps
} from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

/** Data */
export interface IUserInfo {
  headPic?: string
  nickName?: string
  email: string
  captcha: string
}
const formSize = ref<ComponentSize>('default')
const formRef = ref<FormInstance>()
const countdown = ref(0)
const isSendCaptcha = ref(false)
let timer: number | undefined | null = null
const router = useRouter()
let formData = ref<IUserInfo>({
  headPic: '',
  nickName: '',
  email: '',
  captcha: ''
})
const formRules = reactive<FormRules<IUserInfo>>({
  nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})

/** Life Cycle */
onMounted(() => {
  initData()
})

/** Events */
const initData = async () => {
  const res = await getUserInfo()
  if (res.status === 200 || res.status === 201) {
    const { data } = res.data
    formData.value = data
  }
}
const sendCaptcha = async () => {
  const res = await updateUserInfoCaptcha()
  if (res.status === 200 || res.status === 201) {
    ElMessage.success('验证码发送成功')
    startCountdown(60)
  }
}
const startCountdown = (time: number) => {
  countdown.value = time
  isSendCaptcha.value = true
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value === 0) {
      clearInterval(timer as number)
      isSendCaptcha.value = false
    }
  }, 1000)
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const res = await updateUserInfo(formData.value)
      const { code, message: msg, data } = res.data
      if (res.status === 200 || res.status === 201) {
        ElMessage.success('用户信息修改成功')
        // 跳转至登陆页面
        setTimeout(() => {
          router.push({ name: 'login' })
        }, 1500)
      } else {
        ElMessage.error(data || '系统繁忙,请稍后再试')
      }
    } else {
      ElMessage.error('表单校验失败')
    }
  })
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = async (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }

  return true
}
const onUpload: UploadProps['httpRequest'] = async (options) => {
  const res = await presignedUrl(options.file.name)
  if (res.status === 201 || res.status === 200) {
    const file = options.file
    const uploadRes = await axios.put(res.data.data, file)
    if (uploadRes.status === 201 || uploadRes.status === 200) {
      options.onSuccess(uploadRes)
      formData.value.headPic = `http://localhost:9000/meeting-room-booking-system/${file.name!}`
      ElMessage.success('上传成功！')
    }
  }
}

const uploadProps = ref({
  accept: 'image/png, image/jpeg, image/gif',
  beforeUpload: beforeAvatarUpload,
  showFileList: false,
  drag: false,
  httpRequest: onUpload
})
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style scoped lang="less">
#updateUserInfo {
  width: 400px;
  margin: 100px auto 0 auto;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
